package com.lei.springbootpractice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lei.springbootpractice.dao.CategoryDao;
import com.lei.springbootpractice.pojo.CategoryPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
public class CategoryService {
    @Autowired
    private CategoryDao categoryDao;
    
    private CategoryCacheManager cacheManager;

    // 内存缓存 - 提升查询性能
    private Map<String, List<CategoryPojo>> parentCategoriesCache = new ConcurrentHashMap<>();
    private Map<String, List<CategoryPojo>> subCategoriesCache = new ConcurrentHashMap<>();
    private Map<String, CategoryPojo> categoryCache = new ConcurrentHashMap<>();
    private long lastCacheUpdate = 0;
    private static final long CACHE_DURATION = 60000; // 1分钟缓存，确保数据及时更新

    // 获取所有分类
    public List<CategoryPojo> getAllCategories() {
        return categoryDao.selectList(null);
    }

    // 获取父分类 - 带缓存优化
    public List<CategoryPojo> getParentCategories() {
        String cacheKey = "PARENT_CATEGORIES";
        
        // 检查缓存是否有效
        if (isCacheValid() && parentCategoriesCache.containsKey(cacheKey)) {
            System.out.println("从缓存获取父分类数据");
            return parentCategoriesCache.get(cacheKey);
        }
        
        // 从数据库查询
        System.out.println("从数据库查询父分类数据");
        List<CategoryPojo> parentCategories = categoryDao.selectParentCategories();
        
        // 更新缓存
        parentCategoriesCache.put(cacheKey, parentCategories);
        updateCacheTimestamp();
        
        return parentCategories;
    }

    // 获取子分类 - 带缓存优化
    public List<CategoryPojo> getSubcategories(String parentId) {
        if (parentId == null || parentId.trim().isEmpty()) {
            return List.of();
        }
        
        // 检查缓存是否有效
        if (isCacheValid() && subCategoriesCache.containsKey(parentId)) {
            System.out.println("从缓存获取子分类数据，父分类ID：" + parentId);
            return subCategoriesCache.get(parentId);
        }
        
        // 从数据库查询
        System.out.println("从数据库查询子分类数据，父分类ID：" + parentId);
        List<CategoryPojo> subCategories = categoryDao.selectSubcategories(parentId);
        
        // 更新缓存
        subCategoriesCache.put(parentId, subCategories);
        updateCacheTimestamp();
        
        return subCategories;
    }

    // 根据ID获取分类 - 带缓存优化
    public CategoryPojo getCategoryById(String categoryId) {
        if (categoryId == null || categoryId.trim().isEmpty()) {
            return null;
        }
        
        // 检查缓存是否有效
        if (isCacheValid() && categoryCache.containsKey(categoryId)) {
            System.out.println("从缓存获取分类数据，分类ID：" + categoryId);
            return categoryCache.get(categoryId);
        }
        
        // 从数据库查询
        System.out.println("从数据库查询分类数据，分类ID：" + categoryId);
        CategoryPojo category = categoryDao.selectById(categoryId);
        
        // 更新缓存
        if (category != null) {
            categoryCache.put(categoryId, category);
            updateCacheTimestamp();
        }
        
        return category;
    }

    // 批量根据ID获取分类 - 新增方法用于性能优化
    public List<CategoryPojo> getCategoriesByIds(List<String> categoryIds) {
        if (categoryIds == null || categoryIds.isEmpty()) {
            return List.of();
        }
        
        // 先从缓存中获取已有的数据
        List<CategoryPojo> cachedCategories = categoryIds.stream()
            .filter(id -> isCacheValid() && categoryCache.containsKey(id))
            .map(id -> categoryCache.get(id))
            .collect(Collectors.toList());
        
        // 找出缓存中没有的ID
        List<String> missingIds = categoryIds.stream()
            .filter(id -> !isCacheValid() || !categoryCache.containsKey(id))
            .collect(Collectors.toList());
        
        // 查询缺失的数据
        if (!missingIds.isEmpty()) {
            QueryWrapper<CategoryPojo> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("category_id", missingIds);
            List<CategoryPojo> dbCategories = categoryDao.selectList(queryWrapper);
            
            // 更新缓存
            dbCategories.forEach(category -> categoryCache.put(category.getCategoryId(), category));
            updateCacheTimestamp();
            
            // 合并结果
            cachedCategories.addAll(dbCategories);
        }
        
        return cachedCategories;
    }

    // 添加分类
    public boolean addCategory(CategoryPojo category) {
        boolean result = categoryDao.insert(category) > 0;
        if (result) {
            clearCache(); // 清除缓存以确保数据一致性
            System.out.println("添加分类成功，清除缓存");
            // 通知缓存管理器数据已更新
            if (cacheManager != null) {
                cacheManager.markCacheForRefresh();
            }
        }
        return result;
    }

    // 更新分类
    public boolean updateCategory(CategoryPojo category) {
        boolean result = categoryDao.updateById(category) > 0;
        if (result) {
            clearCache(); // 清除缓存以确保数据一致性
            System.out.println("更新分类成功，清除缓存");
            // 通知缓存管理器数据已更新
            if (cacheManager != null) {
                cacheManager.markCacheForRefresh();
            }
        }
        return result;
    }

    // 删除分类
    public boolean deleteCategory(String categoryId) {
        boolean result = categoryDao.deleteById(categoryId) > 0;
        if (result) {
            clearCache(); // 清除缓存以确保数据一致性
            System.out.println("删除分类成功，清除缓存");
            // 通知缓存管理器数据已更新
            if (cacheManager != null) {
                cacheManager.markCacheForRefresh();
            }
        }
        return result;
    }

    /**
     * 获取分类层级结构（用于优化显示）
     */
    public Map<String, List<CategoryPojo>> getCategoryHierarchy() {
        List<CategoryPojo> parentCategories = getParentCategories();
        Map<String, List<CategoryPojo>> hierarchy = new ConcurrentHashMap<>();
        
        for (CategoryPojo parent : parentCategories) {
            List<CategoryPojo> subCategories = getSubcategories(parent.getCategoryId());
            hierarchy.put(parent.getCategoryId(), subCategories);
        }
        
        return hierarchy;
    }

    /**
     * 清除所有缓存
     */
    public void clearCache() {
        parentCategoriesCache.clear();
        subCategoriesCache.clear();
        categoryCache.clear();
        lastCacheUpdate = 0;
        System.out.println("分类缓存已清除");
    }

    /**
     * 检查缓存是否有效
     */
    private boolean isCacheValid() {
        return (System.currentTimeMillis() - lastCacheUpdate) < CACHE_DURATION;
    }

    /**
     * 更新缓存时间戳
     */
    private void updateCacheTimestamp() {
        lastCacheUpdate = System.currentTimeMillis();
    }

    /**
     * 预热缓存
     */
    public void warmUpCache() {
        System.out.println("开始预热分类缓存");
        getParentCategories();
        List<CategoryPojo> parents = getParentCategories();
        for (CategoryPojo parent : parents) {
            getSubcategories(parent.getCategoryId());
        }
        System.out.println("分类缓存预热完成");
    }

    /**
     * 设置缓存管理器 - 用于解决循环依赖
     */
    public void setCacheManager(CategoryCacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }
}
